import Vue from 'vue'
import VueRouter, { RouteConfig } from 'vue-router'

// 引入的组件
import Index from '../components/Index.vue'
import Login from '../components/Login.vue'

Vue.use(VueRouter)
const routes: Array<RouteConfig> = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/index',
    name: 'Index',
    component: Index
  }
]
const router = new VueRouter({
  routes
})

/* 拿到路由对象  添加beforeEach 导航守卫
* to 将要访问的路径
* from 从哪个路径跳转
* next 函数 表示放行  1--next()放行；1--next('/login') 强制放行
* */
router.beforeEach((to, from, next) => {
  // 如果是登录页面 直接放行
  if (to.path == '/login') return next()
  const token = window.sessionStorage.getItem('token')
  if (!token) return next('/login')
  return next()
})

// 暴露router对象
export default router
